<template>
  <div class="common-layout">
    <el-container>
      <el-aside width="200px" style="min-height: 100vh; background-color: rgb(22,46,86)">
        <div class="aside-head-info"
             style="width: 200px; height: 80px; align-items: center; justify-items: center; display: flex">
          <span
              style="color: #f9f9f9; display: flex; align-items: center; justify-content: center; width: 200px">欢迎您，系统管理员</span>
        </div>
        <el-menu style="border: none" :default-active="currentUrl" router background-color="#162E56"
                 text-color="#f9f9f9">
          <el-menu-item index="/top-manager/index">
            <template #title>
              <el-icon>
                <User/>
              </el-icon>
              用户首页
            </template>
          </el-menu-item>
          <el-menu-item index="/top-manager/account-manage">
            <template #title>
              <el-icon>
                <Edit/>
              </el-icon>
              账户管理
            </template>
          </el-menu-item>
          <el-menu-item index="/top-manager/auth-distribute">
            <template #title>
              <el-icon>
                <Lock/>
              </el-icon>
              权限分配
            </template>
          </el-menu-item>
          <el-menu-item index="/top-manager/manage-restaurant">
            <template #title>
              <el-icon>
                <DishDot/>
              </el-icon>
              食堂管理
            </template>
          </el-menu-item>
          <el-menu-item index="/top-manager/remark-control">
            <template #title>
              <el-icon>
                <ChatDotSquare/>
              </el-icon>
              评论管理
            </template>
          </el-menu-item>
          <el-menu-item index="/top-manager/community-surveillance">
            <template #title>
              <el-icon>
                <Camera/>
              </el-icon>
              社区管理
            </template>
          </el-menu-item>
        </el-menu>
      </el-aside>
      <el-container>
        <el-header
            style="box-shadow: 2px 0 6px rgba(0, 21, 41, .36); display: flex; align-items: center; justify-content: space-between">
          <el-breadcrumb :separator-icon="ArrowRight">
            <el-breadcrumb-item v-for="item in route.matched" :to="{path: item.path}">{{ item.meta.title }}
            </el-breadcrumb-item>

          </el-breadcrumb>
          <div class="avatar-container" style="align-items: center; display: flex; justify-content: flex-end">
            <el-dropdown style="display: flex; align-items: center; justify-content: flex-end" placement="bottom">
        <span class="el-dropdown-link"
              style="display: flex; align-items: center;">
          <el-avatar :size="24" :src="avatarSrc" style="margin: 0 5px"/>
          {{ '欢迎您，' + nickname }}
        </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>个人中心</el-dropdown-item>
                  <el-dropdown-item>退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-header>
        <el-main>
          <el-form :model="queryParams" ref="queryForm" size="default" :inline="true" label-width="68px">
            <el-form-item label="食堂名称">
              <el-input
                  v-model="queryParams.restaurantName"
                  placeholder="请输入用户账号"
                  clearable
                  @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="食堂地点">
              <el-input
                  v-model="queryParams.restaurantLocation"
                  placeholder="请输入食堂地点"
                  clearable
                  @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="食堂状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择食堂状态" clearable>
                <el-option
                    v-for="item in dict_status"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :icon="Search" size="default" @click="handleQuery">搜索</el-button>
              <el-button :icon="Refresh" size="default" @click="resetQuery" type="warning">重置</el-button>
            </el-form-item>
          </el-form>

          <el-row>
            <el-col :span="3">
              <el-button :icon="Plus" @click="handleAddRestaurant" type="primary" size="default">新增</el-button>
            </el-col>
          </el-row>

          <!--主体数据表格-->
          <el-table v-loading="tableLoading" :data="tableData">
            <el-table-column label="id" align="center" prop="restaurantId" v-if="false"/>
            <el-table-column label="食堂名称" align="center" prop="restaurantName"/>
            <el-table-column label="食堂照片" align="center">
              <template #default="scope">
                <img :src="scope.row.avatar" style="width: 150px; height: 80px" alt="暂无用户头像"/>
              </template>
            </el-table-column>
            <el-table-column label="食堂位置" align="center" prop="restaurantLocation"/>
            <el-table-column label="食堂状态" align="center" >
              <template #default="scope">
                <el-button :type="scope.row.status==='正常'?'primary':'danger'" size="small" @click="changeRestaurantStatus(scope.row)">{{scope.row.status}}</el-button>
              </template>
            </el-table-column>
            <el-table-column label="开业营业时间" prop="openingTime" align="center"/>
            <el-table-column label="结束营业时间" prop="closingTime" align="center"/>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button
                    size="small"
                    link
                    :icon="Edit"
                    @click="handleUpdate(scope.row)"
                >修改
                </el-button>
                <el-button
                    size="small"
                    link
                    :icon="Delete"
                    @click="handleDelete(scope.row)"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
              v-show="total>0"
              :total="total"
              @change="handlePageSelectChange"/>

<!--          添加、修改对话框-->
          <el-dialog :title="dialogTile" v-model="dialogVis" append-to-body width="400px">
            <el-form :model="form" ref="formRef" :rules="formRules" style="align-items: center">
              <el-form-item label="食堂名称" prop="restaurantName">
                <el-input v-model="form.restaurantName" placeholder="请输入食堂名称"/>
              </el-form-item>
              <el-form-item label="食堂照片">
                <el-upload
                    v-model:file-list="fileList"
                    ref="upload"
                    list-type="picture-card"
                    :on-remove="handleRemove"
                    :auto-upload="false"
                    :limit="1"
                    :on-exceed="handleExceed"
                    :on-change="handleSelectedImgChange">
                  <template #tip>
                    <span style="color: red">限制上传一张图片，超出将被自动替换</span>
                  </template>
                  <el-icon>
                    <Plus/>
                  </el-icon>
                </el-upload>
              </el-form-item>
              <el-form-item label="食堂位置" prop="restaurantLocation">
                <el-input placeholder="请输入食堂位置" v-model="form.restaurantLocation"/>
              </el-form-item>
              <el-form-item label="食堂热线" prop="phone">
                <el-input placeholder="请输入食堂热线" v-model="form.phone"/>
              </el-form-item>
              <el-form-item label="食堂邮箱" prop="restaurantLocation">
                <el-input placeholder="请输入食堂邮箱" v-model="form.email"/>
              </el-form-item>
              <el-form-item label="营业时间" prop="openingTime">
                <el-time-select
                    v-model="form.openingTime"
                    :max-time="form.closingTime"
                    class="mr-4"
                    placeholder="请输入开始营业时间"
                    start="05:30"
                    step="00:15"
                    end="23:30"/>
                <el-time-select
                    v-model="form.closingTime"
                    :min-time="form.openingTime"
                    placeholder="请输入结束营业时间"
                    start="05:30"
                    step="00:15"
                    end="23:30"/>
              </el-form-item>
<!--              <el-form-item label="食堂状态">-->
<!--                <el-select v-model="form.status" placeholder="请选择食堂状态" clearable>-->
<!--                  <el-option-->
<!--                      v-for="item in dict_status"-->
<!--                      :key="item.value"-->
<!--                      :label="item.label"-->
<!--                      :value="item.value"-->
<!--                  />-->
<!--                </el-select>-->
<!--              </el-form-item>-->
              <el-form-item>
                <el-button type="primary" @click="handleFormSubmit(formRef)">确定</el-button>
                <el-button type="danger" @click="handleCancelSubmit">取消</el-button>
              </el-form-item>
            </el-form>
          </el-dialog>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import {useRoute} from "vue-router";
import {ArrowRight, Refresh, Search, Edit, Delete, Plus} from "@element-plus/icons-vue";
import {
  querySatisfiedRestaurant,
  queryDetailedRestaurant,
  addRestaurant,
  updateRestaurant,
  deleteRestaurant, updateRestaurantStatus
} from "../../web-api/system-manager/manage-restaurant";
import {baseStaticRecourseAPI, NOW_ENVIRONMENT} from "../../baseAPIConfig.js";
import {
  dict_status, emptyValidator,
  generalEmailValidator,
  generalPhoneNumberValidator,
  generalValidatorJudgeIfEmpty
} from "../../utils/common.js";
import {ElMessage, ElMessageBox, genFileId} from "element-plus";
import {handleDataSubmitWithBlob} from "../../utils/dongyan.js";
import {getLocalStorage, KEY_AVATAR, KEY_NICKNAME} from "../../utils/localStorge.js";

const changeRestaurantStatus = (row)=>{
  ElMessageBox.confirm(`确定要改变${row.restaurantName}状态吗？`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消"
  }).then(()=>{
    updateRestaurantStatus({restaurantId: row.restaurantId,
      status: row.status==="正常"?"1":"0"}).then(res=>{
      ElMessage.success("修改成功！");
      dialogVis.value = false;
      getList();
      resetForm();
    })
  }).catch(()=>{
    ElMessage.info("状态更改取消！")
  })
}

let total = ref()

const handlePageSelectChange = (newPageNum, newPageSize)=>{
  console.log(newPageNum, newPageSize)
  queryParams.pageSize = newPageSize;
  queryParams.pageNum = newPageNum;
  getList();
}

const handleFormSubmit = (ref)=>{
  ref.validate(valid=>{
    if(valid){
      // 修改
      let formdata = new FormData()
      formdata.append("restaurant", handleDataSubmitWithBlob(form))
      formdata.append("restaurantPic", fileContent.value);
      console.log(form)
      if(form.restaurantId){
        updateRestaurant(formdata).then(res=>{
          ElMessage.success("修改成功！");
          dialogVis.value = false;
          getList();
          resetForm();
        })
      }else{
        addRestaurant(formdata).then(res=>{
          ElMessage.success("新增成功！");
          dialogVis.value = false;
          getList();
          resetForm();
        })
      }
    }
  })
}

const handleCancelSubmit = ()=>{
  dialogVis.value = false;
  resetForm();
}

// 上传文件同步列表
let fileList = ref([{
  name: 'test.png',
  url: 'https://i.b2b168.com/wrzimg.jpg'
}])

// 点击删除图片时触发
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

let upload = ref()

// 超出上传限制时调用
const handleExceed = (files)=>{
  upload.value.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  upload.value.handleStart(file)
}

// 上传内容更改时触发
const handleSelectedImgChange = (ev)=>{
  fileContent.value = ev.raw;
}

// 新增、修改表格规则
let formRules = ref({
  restaurantName: [{validator: generalValidatorJudgeIfEmpty("食堂名称不能为空！"), trigger: "blur"}],
  restaurantLocation: [{validator: generalValidatorJudgeIfEmpty("食堂位置不能为空！"), trigger: "blur"}],
  email: [{validator: generalEmailValidator("邮箱"), trigger: 'blue'}],
  phone: [{validator: generalPhoneNumberValidator("食堂热线"), trigger: 'blur'}],
  openingTime: [{validator: emptyValidator(), trigger: 'blur'}],
  closingTime: [{validator: emptyValidator(), trigger: 'blur'}],
  // status: [{validator: generalValidatorJudgeIfEmpty("食堂营业状态不能为空！"), trigger: 'blur'}]
})

// 对话框
let dialogTile = ref()
let dialogVis = ref(false)

// 新增餐厅
const handleAddRestaurant = ()=>{
  resetForm()
  fileList.value = []
  dialogTile.value = "新增食堂"
  dialogVis.value = true;
}

// 更新餐厅
const handleUpdate = (row)=>{
  queryDetailedRestaurant(row.restaurantId).then(res=>{
    // 更新上传框的图片为实际的用户头像
    fileList.value = [{url: baseStaticRecourseAPI[NOW_ENVIRONMENT]+res.data.avatar,
      name: (baseStaticRecourseAPI[NOW_ENVIRONMENT]+res.data.avatar).split("/").slice(-1)[0]}]
    form.restaurantId = row.restaurantId;
    form.restaurantName = res.data.restaurantName;
    form.restaurantLocation = res.data.restaurantLocation;
    form.email = res.data.email;
    form.phone = res.data.phone;
    form.openingTime = res.data.openingTime;
    form.closingTime = res.data.closingTime;
    // form.status = res.data.status==="0"?"正常":"停用";
    dialogVis.value = true;
    dialogTile.value = "修改食堂信息"
  })
}

// 删除餐厅
const handleDelete = (row)=>{
  ElMessageBox.confirm(`确定要删除${row.restaurantName}的信息吗？`, "警告", {
    cancelButtonText: "取消",
    confirmButtonText: "确定"
  }).then(()=>{
    deleteRestaurant(row.restaurantId).then(res=>{
      if(res.code===200){
        ElMessage.success("删除成功")
        getList()
      }else{
        ElMessage.error("删除失败，食堂已有较多数据，不允许删除！")
        getList()
      }
    }).catch(err=>{console.error(err)})
  }).catch(()=>{
    ElMessage.info("删除取消")
  })
}

let fileContent = ref()

const handleQuery = ()=>{
  queryParams.pageNum = 1;
  getList();
}

const resetQuery = ()=>{
  resetQueryForm();
  handleQuery();
}

// 查询表单
let queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  restaurantName: null,
  restaurantLocation: null,
  status: null
})

// queryParams表单引用
let queryForm = ref()

// queryForm表单重置
const resetQueryForm = ()=>{
  if(!queryForm.value){
    return
  }
  queryForm.value.resetFields();
  queryParams.pageNum = 1;
  queryParams.pageSize = 10;
}

// 新增、修改表单
let form = reactive({
  restaurantId: null,
  restaurantName: null,
  restaurantLocation: null,
  email: null,
  phone: null,
  openingTime: null,
  closingTime: null,
  // avatar
})

// 表单引用
let formRef = ref()

// 重置添加、修改表单
const resetForm = ()=>{
  if(!formRef.value) {
    return
  }
  formRef.value.resetFields()
}

let tableData = ref()
let tableLoading = ref(false)

function getList(){
  tableLoading.value = true
  querySatisfiedRestaurant(queryParams).then(res=>{
    let temp = res.rows;
    temp.map(i=>{
      i.avatar = baseStaticRecourseAPI[NOW_ENVIRONMENT] + i.avatar;
      i.status = i.status==="0"?"正常":"停用";
    })
    total.value = res.total
    tableData.value = temp
    tableLoading.value = false
  })
}

let route = useRoute();

// 记录当前路由
let currentUrl = ref()

// 记录当前登录用户昵称
let nickname = ref(getLocalStorage(KEY_NICKNAME))

// 记录当前用户登陆的食堂id
// let restaurantId = getLocalStorage(KEY_RESTAURANT_ID);

// 记录当前登录用户头像，后期应该要大改
let avatarSrc = baseStaticRecourseAPI[NOW_ENVIRONMENT] + getLocalStorage(KEY_AVATAR)

onBeforeMount(()=>{
  getList();
})

onMounted(() => {
  currentUrl.value = route.path;
  console.log(currentUrl);
  console.log(route)
})
</script>

<style scoped>
.is-active {
  color: #f9f9f9 !important;
  background-color: #47739a;
  border-radius: 20px;
  margin: 0 10px;
}

.el-menu-item {
  margin: 5px 10px !important;
}

.el-menu-item:hover {
  border-radius: 20px;
}
</style>